package cn.shequren.communityPeople.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.jz.community.basecomm.base.BaseHtml5Activity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.modulemine.packet.ui.activity.RedPacketActivity;
import com.jz.community.moduleshopping.coupon.ui.CouponListActivity;
import com.jz.community.moduleshopping.goodsDetail.ui.GoodsDetailActivity;
import com.jz.community.moduleshopping.orderDetail.ui.OrderDetailActivity;
import com.jz.community.moduleshopping.orderDetail.ui.OrderTrackActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;
import cn.shequren.communityPeople.home.ui.activity.MainActivity;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则： 1) 默认用户会打开主界面 2) 接收不到自定义消息
 */
public class JpushReceiver extends BroadcastReceiver {

    private static final String TAG = "JPush";
    private JpushInfo jpushInfo;
    private String act;
    private String id;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction()
                + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            if (bundle == null) {
                return;
            }
            String regId = bundle
                    .getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            // send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
                .getAction())) {
            if (bundle == null){
                return;
            }
            Log.d(TAG,
                    "[MyReceiver] 接收到推送下来的自定义消息: "
                            + bundle.getString(JPushInterface.EXTRA_MESSAGE));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
                .getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            if (bundle == null){
                return;
            }
            int notifactionId = bundle
                    .getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
                .getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            // 打开自定义的Activity
            try {
                processCustomMessage(context, bundle);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent
                .getAction())) {
            if (bundle == null){
                return;
            }
            Log.d(TAG,
                    "[MyReceiver] 用户收到到RICH PUSH CALLBACK: "
                            + bundle.getString(JPushInterface.EXTRA_EXTRA));
            // 在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity，
            // 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent
                .getAction())) {
            boolean connected = intent.getBooleanExtra(
                    JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction()
                    + " connected state change to " + connected);

        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        if (bundle == null){
            return "bundle==null";
        }
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(
                            bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" + myKey + " - "
                                + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    private void processCustomMessage(Context context, Bundle bundle)
            throws Exception {
        if (bundle == null) {
            Intent mIntent = new Intent(context, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
            return;
        }
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);

        if (!Preconditions.isNullOrEmpty(extras)) {
            jpushInfo = JsonUtils.parseObject(extras, JpushInfo.class);
            act = jpushInfo.getExtras().getAct();
            id = jpushInfo.getExtras().getId();
        }

        Log.e(TAG, "extras:" + extras);

        if ("order".equals(act)) {
            //订单已接单（自提）商家订单完成 订单配送（快递）订单被拒------跳转订单详情
            Intent mIntent = new Intent(context, OrderDetailActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("orderId", id);
            context.startActivity(mIntent);
        } else if ("coupon".equals(act)) {
            //优惠券即将失效-------跳转优惠券列表
            Intent mIntent = new Intent(context, CouponListActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
        } else if ("redpackage".equals(act)) {
            //红包即将失效 充值送红包 分享有礼送红包-------跳转红包列表

            Intent mIntent = new Intent(context, RedPacketActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
        } else if ("miaosha".equals(act)) {
            //开抢提醒-------跳转商品详情
            Intent mIntent = new Intent(context, GoodsDetailActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("gid", id);
            context.startActivity(mIntent);
        } else if ("alluser".equals(act)) {
            //营销活动
            String url = jpushInfo.getExtras().getUrl();
            //跳转title
            String title = jpushInfo.getExtras().getTitle();
            Intent mIntent = new Intent(context, BaseX5WebActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("url", url);
            mIntent.putExtra("title", title);
            context.startActivity(mIntent);
        } else if ("express".equals(act)) {
            //快递收件列表
            Intent mIntent = new Intent(context, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("status", 0);
            context.startActivity(mIntent);
        } else if ("express_send_out".equals(act)) {
            //快递发件列表
            Intent mIntent = new Intent(context, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("status", 1);
            context.startActivity(mIntent);
        } else if ("express_send".equals(act)) {
            //快递寄件记录列表
            Intent mIntent = new Intent(context, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("id", id);
            mIntent.putExtra("push", 6);
            context.startActivity(mIntent);
        } else if ("express_sign".equals(act)) {
            Intent mIntent = new Intent(context, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mIntent.putExtra("status", 2);
            context.startActivity(mIntent);
        } else {
            Intent mIntent = new Intent(context, MainActivity.class);
            mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
        }
    }
}
